﻿using AutoMapper;
using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using MediatR;

namespace B.Z.BasicData.API.Write.Application.Menu
{
    public class MenuRemoveCommandHandler : IRequestHandler<MenuRemoveCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Menu> menuRepository;
        private readonly IMapper mapper;

        public MenuRemoveCommandHandler(IBaseRepository<T_Menu> menuRepository, IMapper mapper)
        {
            this.menuRepository = menuRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(MenuRemoveCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
            result.Message = "删除成功";
            //判断是否有子集
            var list = menuRepository.GetAll().Where(x => x.Pid == request.Id||x.Id==request.Id).ToList();

            if (request.IsDelete == false)
            {
                if (list.Count() > 1)
                {
                    result.Code = APIEnum.faile;
                    result.Message = "当前菜单存在子菜单";
                    return await Task.FromResult(result);
                }
                foreach (var item in list)
                {
                    item.IsDelete = true;
                }
                result.Data += menuRepository.UpdateRange(list);
                return await Task.FromResult(result);
            }
            else 
            {
                foreach (var item in list)
                {
                    item.IsDelete = true;
                }
                result.Data += menuRepository.UpdateRange(list);
                return await Task.FromResult(result);
            }
            
            

        }
    }
}
